package com.server.modules.sys.zbus;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.zbus.broker.Broker;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Consumer;
import org.zbus.mq.Consumer.ConsumerHandler;
import org.zbus.net.http.Message;
import com.alibaba.fastjson.JSON;
import com.server.common.utils.PathUtils;
import com.server.modules.sys.dao.customer.impt.CustomerImportDao;
import com.server.modules.sys.dao.customer.impt.CustomerImportLogDao;
import com.server.modules.sys.entity.customer.impt.CustomerImport;
import com.server.modules.sys.entity.customer.impt.CustomerImportLog;
import com.server.modules.sys.service.customer.impt.CustomerImportLogService;
import com.server.modules.sys.service.customer.impt.CustomerImportService;
import com.server.modules.sys.utils.Md5Utils;
import com.server.modules.sys.vo.ImportTempObj;
@Component
public class ConsumerUtils implements IConsumerUtilService{

	@Resource
	private CustomerImportLogService customerImportLogService;
	
	@Resource
	private CustomerImportLogDao customerImportLogDao;
	
	@Resource
	private CustomerImportService customerImportService;
	
	 
	
	 
	 	@Transactional(readOnly = false)
	    public boolean uploadFile(MultipartFile file,CustomerImportLog customerImportLog,File file0) {
	        Calendar cal = Calendar.getInstance();
	        int year = cal.get(Calendar.YEAR);
	        int month = cal.get(Calendar.MONTH) + 1;
	        int day = cal.get(Calendar.DATE);
	        String dateDir =  year + File.separator + month
	                + File.separator + day + File.separator;
	        File tmpDir = new File(PathUtils.getSaveImagePath()+dateDir);
	        if (!tmpDir.exists()) {
	            tmpDir.mkdirs();
	        }
	        // 构造新的图片名称
	        String fileName = file.getOriginalFilename() ;  
	        String savePath = PathUtils.getSaveImagePath()+ dateDir ;
	        File targetFile = new File(savePath, fileName);  
	         if(!targetFile.exists()){  
	             targetFile.mkdirs();  
	         }  
	         //保存  
	         try {  
	        	 String fileMD5 = Md5Utils.getFileMD5(targetFile);
	        	 int countByMd5 = customerImportLogService.countByMd5(fileMD5);
	        	 //之前上传过
	        	 if(countByMd5>0){
	        		 customerImportLog.setMd5(fileMD5);
	        		 return false;
	        	 }else{
	        		 file.transferTo(targetFile);  
	        		 file0=targetFile;
		             customerImportLog.setMd5(fileMD5);
		     		 customerImportLog.setFilename(fileName);
		     		 customerImportLog.setFilesize(file.getSize()+"");
		     		 customerImportLog.setFileurl(targetFile.getPath());
		     		 return true; 
	        	 }
	        	 
	         } catch (Exception e) {  
	             e.printStackTrace();  
	         } finally {
			} 
	         return false;
	      
	    }
	 
	 @Transactional(readOnly = false)
	public  void  consumerImportInDbList(String mqName) throws IOException, InterruptedException{
		//Broker broker = new ZbusBroker("http://101.201.82.116:15555/");   
		Broker broker = new ZbusBroker("127.0.0.1:15555");
		Consumer consumer = new Consumer(broker, mqName);  
		System.out.println("消费初始化："+mqName);
		consumer.start(new ConsumerHandler() { 
			@Override
			public void handle(Message msg, Consumer consumer) throws IOException { 

				try {
						ImportTempObj obj =JSON.parseObject(msg.getBodyString(), ImportTempObj.class);
						// 开时时间
						Long begin = new Date().getTime();
						CustomerImportLog log = obj.getLog();
						StringBuilder failureMsg = obj.getFailureMsg();
						List<CustomerImport> listValid = obj.getList();
						int successNum = obj.getSuccessNum();
						int failureNum = obj.getFailureNum();
						System.out.println("消费：+++++"+listValid.size());
						successNum=customerImportService.BatchInsert(listValid, log.getBatchNo(), log.getType(), log.getFilename());
						if (obj.getExpectCount()-successNum > 0) {
							failureMsg.insert(0, "，失败 " + failureNum + " 条客户，导入信息如下：");
						}
						log.setExpectCount(obj.getExpectCount() + "");
						log.setValidCount(successNum + "");
						log.setRemarks("【系统自动导入】：导入成功");
						log.setIsNewRecord(false);
						log.preInsert();
						customerImportLogDao.insert(log);
						// 结束时间
						Long end = new Date().getTime();
						System.out.println("入库操作cast : " + (end - begin) / 1000F + "s");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
				}
			}
		});   
	}
}
